package cn.opencodes.framework.tools.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

/**
 * GET或POST请求工具类
 * @author HJ
 */
public class HttpUtil {
    private final static String requestEncoding = "UTF-8";
    
    /*public static void main(String[] args) {
    	String url = "https://www.airbridgecargo.com/en/tracking/";
    	String body = doGet(url);
    	System.out.println(body);
	}*/
    
    /**  
     * GET请求，字符串形式数据  
     * @param url 请求地址  
     */
    public static String doGet(String url) {
    	return doGet(url, requestEncoding);
    }
    /**  
     * GET请求，字符串形式数据  
     * @param url 请求地址  
     * @param charset 编码方式  
     */
    public static String doGet(String url, String charset) {  
        StringBuffer result = new StringBuffer();  
        BufferedReader in = null;  
        try {  
            URL realUrl = new URL(url);  
            // 打开和URL之间的连接  
            URLConnection connection = realUrl.openConnection();  
            // 设置通用的请求属性  
            connection.setRequestProperty("accept", "*/*");  
            connection.setRequestProperty("connection", "Keep-Alive");  
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //设置鉴权属性
            //connection.setRequestProperty("X-Authorization", " Bearer " + String.valueOf(param.get("token")));
            // 建立实际的连接  
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));  
            String line;  
            while ((line = in.readLine()) != null) {  
                result.append(line);
            }  
        } catch (Exception e) {  
            System.out.println("发送GET请求出现异常！" + e);  
            e.printStackTrace();  
        }  
        // 使用finally块来关闭输入流  
        finally {  
            try {  
                if (in != null) {  
                    in.close();  
                }  
            } catch (Exception e2) {  
                e2.printStackTrace();  
            }  
        }  
        return result.toString();  
    }
    
    /**  
     * POST请求，字符串形式数据  
     * @param url 请求地址  
     * @param parameters 请求数据  
     */
    public static String doPost(String url, Map<String, String> parameters){
    	return doPost(url, parameters, requestEncoding);
    }
    /**  
     * POST请求，字符串形式数据  
     * @param url 请求地址  
     * @param parameters 请求数据  
     * @param charset 编码方式  
     */
    public static String doPost(String url, Map<String, String> parameters, String charset) {
    	String param = fmtParams(parameters, charset);
    	return doPost(url, param, charset);
    }
    /**  
     * POST请求，字符串形式数据  
     * @param url 请求地址  
     * @param param 请求数据  
     */
    public static String doPost(String url, String param){
    	return doPost(url, param, requestEncoding);
    }
    /**  
     * POST请求，字符串形式数据  
     * @param url 请求地址  
     * @param param 请求数据  
     * @param charset 编码方式  
     */
    public static String doPost(String url, String param, String charset) {  
        PrintWriter out = null;  
        BufferedReader in = null;  
        StringBuffer result = new StringBuffer();   
        try {  
            URL realUrl = new URL(url);  
            // 打开和URL之间的连接  
            URLConnection conn = realUrl.openConnection();  
            // 设置通用的请求属性  
            conn.setRequestProperty("accept", "*/*");  
            conn.setRequestProperty("connection", "Keep-Alive");  
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
            //conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
            // 发送POST请求必须设置如下两行  
            conn.setDoOutput(true);  
            conn.setDoInput(true);  
            // 获取URLConnection对象对应的输出流  
            out = new PrintWriter(conn.getOutputStream());  
            // 发送请求参数  
            out.print(param);  
            // flush输出流的缓冲  
            out.flush();  
            // 定义BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));  
            String line;  
            while ((line = in.readLine()) != null) {  
                result.append(line);
            }  
        } catch (Exception e) {  
            System.out.println("发送 POST 请求出现异常！" + e);  
            e.printStackTrace();  
        }  
        // 使用finally块来关闭输出流、输入流  
        finally {
            try {
                if (out != null) {  
                    out.close();  
                }  
                if (in != null) {  
                    in.close();  
                }  
            } catch (IOException ex) {  
                ex.printStackTrace();  
            }  
        }  
        return result.toString();  
    }  
    

	private static String fmtParams(Map<String, String> parameters, String vchartset){
		StringBuffer params = new StringBuffer();
		for (Iterator<?> iter = parameters.entrySet().iterator(); iter.hasNext();) {
		    try {
		    	Entry<?, ?> element = (Entry<?, ?>) iter.next();
		    	params.append(element.getKey().toString());
		    	params.append("=");
				params.append(URLEncoder.encode(element.getValue().toString(), vchartset));
				params.append("&");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}

		if (params.length() > 0) {
		    params = params.deleteCharAt(params.length() - 1);
		}
		return params.toString();
	}
    
    
  
    /**
	 * 信任任何站点，实现https页面的正常访问
	 */
	public static void trustEveryone() {
        try {  
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;  
                }
            });  
  
            SSLContext context = SSLContext.getInstance("TLS");  
            context.init(null, new X509TrustManager[] { new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }
  
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }
  
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];  
                }
            } }, new SecureRandom());  
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        } catch (Exception e) {
             e.printStackTrace();  
        }
    }
}